package com.enzo.prms.common.exception.util;

import java.util.List;

import com.enzo.prms.common.exception.base.BaseAppException;
import com.enzo.prms.common.exception.base.BaseAppRuntimeException;
import com.enzo.prms.common.exception.base.handler.DefaultHandler;
import com.enzo.prms.common.exception.base.handler.ExceptionHandler;
import com.enzo.prms.common.exception.context.ExceptionContext;

/**
 * The tool for Exception
 * @author ChenYiqun
 *
 */
public class ExceptionUtil {
	private static final ExceptionContext context=ExceptionContext.getInstance();
	
	public static final void handlerException(Exception e){
		//获得异常对应的处理器
		List<ExceptionHandler> handlers=context.getExceptionHandlers(e.getClass());
		if(handlers==null||handlers.size()==0){
			//如果异常没有指定的处理器，就使用默认的异常处理器
			ExceptionHandler defaultHandler=context.getExceptionHandler(DefaultHandler.class);
			if(e instanceof BaseAppRuntimeException){
				BaseAppRuntimeException bex=(BaseAppRuntimeException)e;
				defaultHandler.handler(bex.getErrorCode()==null?"BAR001":bex.getErrorCode(), bex);
			}else if (e instanceof BaseAppException) {
				BaseAppException bex=(BaseAppException)e;
				defaultHandler.handler(bex.getErrorCode()==null?"BA001":bex.getErrorCode(), bex);
			}else{
				defaultHandler.handler("", e);
			}
		}else{
			String errorCode=context.getErrorCode(e.getClass());
			for(ExceptionHandler handler:handlers){
				handler.handler(errorCode,e);
			}
		}
	}
	
	public static final String getErrorCode(Exception e){
		return context.getErrorCode(e.getClass());
	}

}
